package cn.trkj.client.controller;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * @author: wyg
 * @date: 2023/11/8
 * @description:
 */
public class FileXh {

    public static List<File> getFilesList(File file, List<File> temp) {
        File[] listFiles = file.listFiles();
        for (File file2 : listFiles) {
            if (file2.isDirectory()) {
                getFilesList(file2, temp);
            } else {
                temp.add(file2);
            }
        }
        return temp;
    }

//    public static void main(String[] args) {
//        String dateUtil = DateUtils.getDateUtil();
//        File file = new File("F:\\"+dateUtil);
//        ArrayList<File> objects = new ArrayList<File>();
//        List<File> filesList = getFilesList(file, objects);
//        for (File f : filesList) {
//            System.out.println(f.getAbsolutePath());
//        }
//    }

    public static MultipartFile fileToMultipartFile(File file) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem(file.getName(), "text/plain", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new CommonsMultipartFile(item);
    }

}
